<?php
declare (strict_types=1);

namespace app\command;

use think\console\Input;
use think\console\Output;
use think\console\Command;
use think\console\input\Argument;

class MakeDefaultClass extends Command
{

    protected function configure()
    {
        $this->setName('make:default-class')
            ->addArgument('dir', Argument::REQUIRED, "Directory name")
            ->addArgument('class', Argument::REQUIRED, "Class name")
            ->setDescription('create module class');
    }

    protected function execute(Input $input, Output $output)
    {
        $dir   = trim($input->getArgument('dir'));
        $class = trim($input->getArgument('class'));
        $class = _words_capitalized($class);

        $basePath   = $this->app->getBasePath() . 'common' . DIRECTORY_SEPARATOR;
        $module_list = ['logic', 'model', 'services'];
        foreach ($module_list as $module) {
            $suffix    = _words_capitalized($module);
            $classname = $class . $suffix . '.php';
            $pathname  = $basePath . $module . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $classname;
            if (is_file($pathname)) {
                $output->writeln('class ' . $classname . ' already exists!');
            }
            if (!is_dir(dirname($pathname))) {
                mkdir(dirname($pathname), 0755, true);
            }
            $stub      = $this->getStubContent($module);
            $class_file = str_replace(['{%dirName%}', '{%className%}'], [$dir, $class], $stub);
            file_put_contents($pathname, $class_file);
        }
        $output->writeln('success');
    }

    public function getStubContent($module)
    {
        $stub_path = __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR;
        return file_get_contents($stub_path . $module . '.stub');
    }
}
